import 'dart:convert';
import 'dart:io';
import '../models/models.dart';
import '../utils/crypto_util_v2.dart';

/// 简化的HTTP客户端，用于演示加密通讯
class SimpleApiClient {
  static const String baseUrl = 'http://localhost:8080';
  
  /// 发送HTTP请求
  static Future<Map<String, dynamic>> _sendRequest(
    String method,
    String endpoint,
    {Map<String, dynamic>? data}
  ) async {
    try {
      final uri = Uri.parse('$baseUrl$endpoint');
      final client = HttpClient();
      
      late HttpClientRequest request;
      if (method == 'GET') {
        request = await client.getUrl(uri);
      } else if (method == 'POST') {
        request = await client.postUrl(uri);
      } else {
        throw Exception('Unsupported HTTP method: $method');
      }
      
      request.headers.set('Content-Type', 'application/json');
      
      if (data != null) {
        final jsonData = jsonEncode(data);
        request.add(utf8.encode(jsonData));
      }
      
      final response = await request.close();
      final responseBody = await response.transform(utf8.decoder).join();
      
      if (response.statusCode >= 200 && response.statusCode < 300) {
        return jsonDecode(responseBody);
      } else {
        throw Exception('HTTP ${response.statusCode}: $responseBody');
      }
    } catch (e) {
      throw Exception('Network error: $e');
    }
  }
  
  /// 发送加密请求
  static Future<T> _sendEncryptedRequest<T>(
    String method,
    String endpoint,
    Map<String, dynamic> data,
    T Function(Map<String, dynamic>) fromJson,
  ) async {
    try {
      // 1. 加密数据
      final jsonString = jsonEncode(data);
      print('🔍 Original JSON: $jsonString');
      
      final encryptedData = CryptoUtil.encrypt(jsonString);
      print('🔐 Encrypted data: ${encryptedData.substring(0, 50)}...');
      
      // 2. 发送请求
      final response = await _sendRequest(method, '/api$endpoint', data: {
        'data': encryptedData,
      });
      
      print('📥 Response: $response');
      
      // 3. 解析响应
      final encryptedResponse = EncryptedResponse.fromJson(response);
      if (!encryptedResponse.success) {
        throw Exception(encryptedResponse.message);
      }
      
      // 4. 解密响应
      final decryptedData = CryptoUtil.decrypt(encryptedResponse.data);
      print('🔓 Decrypted response: $decryptedData');
      
      final jsonData = jsonDecode(decryptedData);
      
      return fromJson(jsonData);
    } catch (e) {
      print('❌ Encrypted request failed: $e');
      throw Exception('Encrypted request failed: $e');
    }
  }
  
  /// 发送加密GET请求
  static Future<T> _sendEncryptedGetRequest<T>(
    String endpoint,
    T Function(Map<String, dynamic>) fromJson,
  ) async {
    try {
      final response = await _sendRequest('GET', '/api$endpoint');
      
      final encryptedResponse = EncryptedResponse.fromJson(response);
      if (!encryptedResponse.success) {
        throw Exception(encryptedResponse.message);
      }
      
      final decryptedData = CryptoUtil.decrypt(encryptedResponse.data);
      final jsonData = jsonDecode(decryptedData);
      
      return fromJson(jsonData);
    } catch (e) {
      throw Exception('Encrypted GET request failed: $e');
    }
  }
  
  /// 健康检查
  static Future<Map<String, dynamic>> healthCheck() async {
    return await _sendRequest('GET', '/health');
  }
  
  /// 登录
  static Future<LoginResponse> login(String username, String password) async {
    final loginRequest = LoginRequest(username: username, password: password);
    return await _sendEncryptedRequest(
      'POST',
      '/login',
      loginRequest.toJson(),
      (json) => LoginResponse.fromJson(json),
    );
  }
  
  /// 获取用户信息
  static Future<UserData> getUser() async {
    return await _sendEncryptedGetRequest(
      '/user',
      (json) => UserData.fromJson(json),
    );
  }
  
  /// 获取用户列表
  static Future<List<UserData>> getUsers() async {
    final response = await _sendRequest('GET', '/api/users');
    
    final encryptedResponse = EncryptedResponse.fromJson(response);
    if (!encryptedResponse.success) {
      throw Exception(encryptedResponse.message);
    }
    
    final decryptedData = CryptoUtil.decrypt(encryptedResponse.data);
    final jsonData = jsonDecode(decryptedData);
    
    if (jsonData is List) {
      return jsonData.map((item) => UserData.fromJson(item)).toList();
    } else {
      throw Exception('Expected list response');
    }
  }
  
  /// 创建用户
  static Future<UserData> createUser(UserData user) async {
    return await _sendEncryptedRequest(
      'POST',
      '/users',
      user.toJson(),
      (json) => UserData.fromJson(json),
    );
  }
}
